package fe.pong.tennis;

import fe.pong.tennis.input.InputTouch;
import flash.display.DisplayObject;
import flash.display.Sprite;
import fe.pong.tennis.gameElements.GameElement;
import fe.pong.tennis.gameElements.Image;
import fe.pong.tennis.gameElements.Pelota;
import fe.pong.tennis.input.InputConfiguration;
import fe.pong.tennis.input.InputManager;
import fe.pong.tennis.input.InputManagerMouse;
import fe.pong.tennis.input.InputManagerTouch;
import fe.pong.tennis.screens.ScreenManager;
import fe.pong.tennis.screens.GamePlayScreen;
import fe.pong.tennis.screens.MenuScreen;
import haxe.Timer;

class Main extends Sprite {

	private static var _ANCHO_PANTALLA;
	private static var _ALTO_PANTALLA;

	private var screenManager : ScreenManager;
	private var beginTime : Float;

	public function new () {
		super();
		_ANCHO_PANTALLA = stage.stageWidth;
		_ALTO_PANTALLA = stage.stageHeight;
		beginTime = Timer.stamp();

		screenManager = new ScreenManager(stage);
		addChild(screenManager);

		var areaLocal: Sprite = newArea(0);
		var areaVisitante: Sprite = newArea(_ALTO_PANTALLA / 2);
		addChild(areaLocal);
		addChild(areaVisitante);

		var input1: InputManager;
		var input2: InputManager;
		#if android
			input1 = new InputManagerTouch(areaLocal);
			input2 = new InputManagerTouch(areaVisitante);
		#else
			input1 = new InputManagerMouse(areaLocal);
			input2 = new InputManagerMouse(areaVisitante);
		#end
		screenManager.suscribeScreen('game', new GamePlayScreen(screenManager, new InputTouch(input1), new InputTouch(input2)));
		screenManager.suscribeScreen('menu', new MenuScreen(screenManager));
		
		stage.addEventListener(flash.events.Event.ENTER_FRAME, gameLoop);
		stage.addEventListener(flash.events.Event.RESIZE,onResize);
	}

	private function newArea(y: Float): Sprite {
		var area: Sprite = new Sprite();
		area.addChild(new Image("images/transparent.png", 1));
		area.width = _ANCHO_PANTALLA;
		area.height = _ALTO_PANTALLA / 2;
		area.x = 0;
		area.y = y;
		return area;
	}

	function gameLoop(e) {		
		screenManager.updateLogic((Timer.stamp()- beginTime) * 10);
	}

	function onResize(e){
		var scaleX:Float = stage.stageWidth / _ANCHO_PANTALLA;
		var scaleY:Float = stage.stageHeight / _ALTO_PANTALLA;
		this.scaleX = this.scaleY = Math.min(scaleX, scaleY);
		this.x = (stage.stageWidth - (_ANCHO_PANTALLA * this.scaleX)) / 2;
		this.y = (stage.stageHeight - (_ALTO_PANTALLA * this.scaleY)) / 2;
	}

}